package com.naodong.shenluntiku.intergation.voice;

import android.media.MediaPlayer;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;

import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

import me.shingohu.man.util.ToastUtil;

/**
 * Created by hujie on 16/5/25.
 */
public class PlayVoiceManager {

    private String mp3Path; //MP3的路径 有可能是本地路径 有可能是服务器路径
    private MediaPlayer player;
    private PlayVoiceListener listener;

    private PlayVoiceStatus status = PlayVoiceStatus.IDEL;
    private Timer mTimer;
    private TimerTask mTimerTask;

    private boolean isTracking = false;//是否在拖动

    public PlayVoiceManager(String mp3Path, PlayVoiceListener listener) {
        this.mp3Path = mp3Path;
        this.listener = listener;
        init();
    }

    private void init() {
        player = new MediaPlayer();
        player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                setStatus(PlayVoiceStatus.COMPLETE);
                listener.onComplete();
            }
        });

        player.setOnErrorListener(new MediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {
                listener.onError();
                return false;
            }
        });
        player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                setStatus(PlayVoiceStatus.PREPARED);
                listener.onPrepared();
                onProgress();
            }
        });
        initMp3();
    }


    //设置是否在拖动
    public void setTracking(boolean isTracking) {
        this.isTracking = isTracking;
    }


    /**
     * 是否正在播放
     * @return
     */
    private boolean isPlaying() {
        if (player != null && status != PlayVoiceStatus.IDEL && status != PlayVoiceStatus.LOADING && status != PlayVoiceStatus.PREPARED && status != PlayVoiceStatus.RELEASE) {
            try {
                return player.isPlaying();
            } catch (IllegalStateException e) {
                e.printStackTrace();
            }
        }
        return false;
    }


    /**
     * 设置进度
     */
    private void setProgressTask() {

        cancel();
        mTimer = new Timer();
        mTimerTask = new TimerTask() {
            @Override
            public void run() {
                if (!isTracking) {
                    handler.sendEmptyMessage(0);
                }
            }
        };
        mTimer.schedule(mTimerTask, 0, 300);
    }

    /**
     * 取消进度任务
     */
    private void cancel() {
        if (mTimer != null && mTimerTask != null) {
            mTimerTask.cancel();
            mTimer.cancel();
        }
    }

    Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            if (getStatus() == PlayVoiceStatus.START) {
                onProgress();
            }
        }
    };

    private void onProgress() {
        int currentPosition = getCurrentPosition();
        int duration = getDuration();
        listener.onProgress(currentPosition, duration);
    }


    public void play() {

        if (getStatus() != PlayVoiceStatus.IDEL && getStatus() != PlayVoiceStatus.LOADING && getStatus() != PlayVoiceStatus.RELEASE) {
            player.start();
            setProgressTask();
            setStatus(PlayVoiceStatus.START);
        }
    }

    /**
     * 重新播放
     */
    public void resume() {
        if (player != null) {
            if (!isPlaying()) {
                player.start();
                setStatus(PlayVoiceStatus.START);
            }
        }
    }


    private void initMp3() {
        try {
            player.reset();
            player.setDataSource(mp3Path);
            setStatus(PlayVoiceStatus.LOADING);
            player.prepareAsync();//异步准备
        } catch (IOException e) {
            e.printStackTrace();
            Log.e("playMp3", "播放出错");
            listener.onError();
            ToastUtil.makeToast("播放出错");
        }
    }


    /**
     * 设置进度
     * @param seekTo
     */
    public void seekTo(int seekTo) {
        if (player != null) {
            if (status != PlayVoiceStatus.IDEL && status != PlayVoiceStatus.PREPARED && status != PlayVoiceStatus.LOADING && status != PlayVoiceStatus.RELEASE) {
                player.seekTo(seekTo * 1000);
            }
        }
    }

    /**
     * 暂停
     */
    public void pause() {
        if (isPlaying()) {
            player.pause();
            setStatus(PlayVoiceStatus.PAUSR);
        }
    }

    /**
     * 停止
     */
    public void stop() {
        if (isPlaying()) {
            player.stop();
            setStatus(PlayVoiceStatus.STOP);
        }
    }

    /**
     * 释放
     */
    public void release() {
        if (player != null) {
            cancel();
            if (isPlaying()) {
                player.stop();
            }
            player.release();
            setStatus(PlayVoiceStatus.RELEASE);

        }
    }

    /**
     * 获得时长
     * @return
     */
    public int getDuration() {
        if (player != null && getStatus() != PlayVoiceStatus.IDEL && getStatus() != PlayVoiceStatus.LOADING && getStatus() != PlayVoiceStatus.RELEASE) {
            return player.getDuration() / 1000;
        }
        return 0;
    }

    /**
     * 获取当前的位置
     * @return
     */
    public int getCurrentPosition() {
        if (player != null && getStatus() != PlayVoiceStatus.IDEL && getStatus() != PlayVoiceStatus.LOADING && getStatus() != PlayVoiceStatus.RELEASE) {
            return player.getCurrentPosition() / 1000;
        }
        return 0;
    }

    public synchronized PlayVoiceStatus getStatus() {
        return status;
    }

    private synchronized void setStatus(PlayVoiceStatus status) {
        this.status = status;
        listener.onPlayMp3StatusChange(status);
    }
}
